import { createCrudApi } from '../factories/createCrudApi'
import request from '../request'
import type {
  Lead,
  LeadCreate,
  LeadUpdate,
  PropertyMatchListResponse,
  PropertyMatchParams
} from '../types'

/**
 * 客户筛选参数
 */
interface LeadFilter {
  name?: string
  phone?: string
  demand_type?: string
  [key: string]: unknown
}

/**
 * 客户管理 API
 * 使用 createCrudApi 工厂快速生成标准 CRUD 方法
 */
const baseCrudApi = createCrudApi<Lead, LeadCreate, LeadUpdate, LeadFilter>('v1/leads/')

/**
 * AI 提取结果接口
 */
interface ExtractFromNotesResponse {
  success: boolean
  data: {
    budget_range?: string
    demand_type?: string
    layout?: string
    area_preferences?: string[]
  }
  message: string
}

/**
 * 扩展客户 API - 添加智能匹配功能和 AI 提取
 */
export const leadApi = {
  ...baseCrudApi,

  /**
   * 智能匹配房源 (AI增强)
   * @param leadId 客户ID
   * @param params 匹配参数
   * @returns 匹配结果列表
   */
  async matchProperties(leadId: number, params?: PropertyMatchParams): Promise<PropertyMatchListResponse> {
    const response = await request.get<PropertyMatchListResponse>(`/v1/leads/${leadId}/match-properties`, { params })
    return response.data
  },

  /**
   * 从备注中提取关键信息（轻量级）
   * 用于传统表单的智能补全
   * @param notes 备注文本
   * @param existingData 已有字段数据（避免覆盖）
   * @returns 提取结果
   */
  async extractFromNotes(notes: string, existingData?: Record<string, unknown>): Promise<ExtractFromNotesResponse> {
    const response = await request.post<ExtractFromNotesResponse>('/v1/leads/extract-from-notes', {
      notes,
      existing_data: existingData
    })
    return response.data
  }
}
